<template>
  <n-drawer v-model:show="isDrawer" :width="width" :auto-focus="false" @after-leave="handleReset">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
      >
        <n-form-item label="登录账号" path="username">
          <n-input
            placeholder="请输入登录账号"
            v-model:value="formParams.username"
            :disabled="formParams.id ? true : false"
          />
        </n-form-item>
        <n-form-item label="昵称" path="nickname">
          <n-input placeholder="请输入昵称" v-model:value="formParams.nickname" />
        </n-form-item>
        <n-form-item label="所属部门" path="dept_id">
          <n-tree-select
            label-field="dept_name"
            value-field="dept_id"
            key-field="dept_id"
            :options="deptList"
            clearable
            v-model:value="formParams.dept_id"
            placeholder="请选择部门"
          />
        </n-form-item>
        <n-form-item label="所属岗位" path="post_id">
          <n-select
            label-field="post_name"
            value-field="post_id"
            :options="postDataList"
            clearable
            multiple
            v-model:value="formParams.post_id"
            placeholder="请选择所在岗位"
          />
        </n-form-item>
        <n-form-item label="密码" :path="!formParams.id ? 'password' : ''">
          <n-input
            type="password"
            show-password-on="mousedown"
            placeholder="请输入密码"
            v-model:value="formParams.password"
          />
        </n-form-item>
        <n-form-item label="确认密码" :path="!formParams.id ? 'passwordRe' : ''">
          <n-input
            type="password"
            show-password-on="mousedown"
            placeholder="请输入密码"
            v-model:value="formParams.passwordRe"
          />
        </n-form-item>

        <n-form-item label="角色" path="roleId">
          <n-select clearable v-model:value="formParams.roleIds" :options="getRoleList" multiple />
        </n-form-item>

        <n-form-item label="手机" path="mobile">
          <n-input placeholder="请输入手机" v-model:value="formParams.mobile" />
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入邮箱" v-model:value="formParams.email" />
        </n-form-item>
        <!-- <n-form-item label="性别" path="sex">
          <n-radio-group v-model:value="formParams.sex" name="sexGroup">
            <n-space>
              <n-radio v-for="item in sexList" :key="item.dictValue" :value="item.dictLabel">
                {{ item.dictLabel }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item> -->
        <n-form-item label="性别" path="sex">
          <n-radio-group v-model:value="formParams.sex" name="sexGroup">
            <n-space>
              <n-radio :value="0">男</n-radio>
              <n-radio :value="1">女</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="个人介绍" path="remark">
          <n-input type="textarea" placeholder="请输入个人介绍" v-model:value="formParams.remark" />
        </n-form-item>
        <n-form-item label="是否启用" path="deleteStatus">
          <n-radio-group v-model:value="formParams.deleteStatus" name="statusGroup">
            <n-space>
              <n-radio :key="1" :value="1">启用</n-radio>
              <n-radio :key="2" :value="2">禁用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import type { formParamsType } from './types';
  import { useDictionary } from '@/hooks/web/useDictionary';

  import { addUsur, editUsur, userInfo } from '@/api/system/user';
  import { deptTreeList } from '@/api/auth/dept';
  import { postList } from '@/api/auth/post';
  import { SelectMixedOption } from 'naive-ui/es/select/src/interface';

  const rules: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    nickname: {
      required: true,
      message: '昵称不能为空',
      trigger: 'blur',
    },
    roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'number',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    passwordRe: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    dept_id: {
      required: true,
      message: '部门不能为空',
      trigger: 'change',
      type: 'number',
    },
  };

  const emit = defineEmits(['change']);
  const { getDictTypeList } = useDictionary();

  const props = defineProps({
    title: {
      type: String,
      default: '添加会员',
    },
    width: {
      type: Number,
      default: 450,
    },
    roleList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    id: null,
    roleIds: [],
    deleteStatus: 1,
    email: '',
    mobile: '',
    nickname: '',
    password: '',
    passwordRe: '',
    remark: '',
    sex: 0,
    username: '',
    post_id: [],
    dept_id: null,
  });

  const sexList = ref<any[]>();
  const deptList = ref<any[]>();
  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const postDataList = ref([]);

  const formParams = ref<formParamsType>(defaultValueRef());

  const getRoleList = computed(() => {
    return props.roleList as SelectMixedOption[];
  });

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        if (formParams.value.password != formParams.value.passwordRe) {
          return message.error('两次密码不一致');
        }
        const msg = formParams.value.id ? '编辑成功' : '添加成功';
        if (formParams.value.id) {
          editUsur(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          addUsur(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value.restoreValidation();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    userInfo({ id: formParams.value.id }).then((res) => {
      const params = {
        id: formParams.value.id,
        delete_status: parseInt(res.delete_status),
        email: res.email,
        mobile: res.mobile,
        nickname: res.nickname,
        password: '',
        passwordRe: '',
        remark: res.remark,
        sex: res.sex,
        username: res.username,
        roleIds: res.roleIds,
        post_id: res.post_id,
        dept_id: res.dept_id,
      };
      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

  onMounted(async () => {
    const list = await getDictTypeList({ dictType: 'sys_user_sex' });
    sexList.value = list;
    const deptResList = await deptTreeList();
    deptList.value = deptResList;
    const postListRes = await postList({ noPage: true });
    postDataList.value = postListRes.list;
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
